<template>
  <!-- 图表展示区 -->
  <div class="charts-container" v-show="advanceCharts">
    <!-- 新增的待审核人数展示区块 -->
    <div class="audit-count-card">
      <div class="count-header">
        <el-icon class="notification-icon">
          <Bell />
        </el-icon>
        <span class="count-title">待审核数量</span>
      </div>
      <div class="count-content">
        <span class="highlight-number">{{ total }}</span>
        <span class="unit">人</span>
      </div>
      <div class="count-footer">当前待处理申请</div>
    </div>
    <!-- 饼图容器 -->
    <div ref="pieChart" class="chart-item" style="width: 600px; height: 350px;"></div>
  </div>

  <!-- 图表按钮 -->
  <div class="advanced-btn-container">
    <button @click="toggleAdvancedCharts" class="secondary-btn">
      {{ advanceCharts ? '收起图表' : '展开图表' }}
    </button>
  </div>

  <!-- 顶部功能区 -->
  <div id="top">
    <!-- 条件查询输入框 -->
    学院：<input type="text" v-model="qCollege">
    专业：<input type="text" v-model="qMajor">
    <!-- 表格功能区 -->
    <el-button type="primary" @click="conditionPageQuery(currentPage, pageSize)">
      <el-icon>
        <Search />
      </el-icon>搜索
    </el-button>
    <el-button type="primary" @click="agreeApply" color="green">
      <el-icon><Select /></el-icon>同意申请
    </el-button>
    <el-button type="primary" @click="exportInfoToExcel" color="#00ba5e">
      <img src="../../assets//icons/Excel.svg" alt="icon" style="width: 18px; height: 18px; margin-right: 8px;" />
      导出为Excel
    </el-button>
    <el-button type="primary" @click="exportInfoToPDF" color="#ee0000">
      <img src="../../assets//icons/PDF图标.svg" alt="icon" style="width: 18px; height: 18px; margin-right: 8px;" />
      导出为PDF
    </el-button>
  </div>



  <!-- 选择表格需要展示的列 -->
  <div class="columnSelector">
    <div class="selectorTitle">当前呈现的列：</div>
    <el-select v-model="selectedColumns" multiple placeholder="请选择要显示的列">
      <el-option v-for="column in columnOptions" :key="column.value" :label="column.label" :value="column.value" />
    </el-select>
  </div>
  <!-- 表格展示区 -->
  <div class="tableShow">
    <el-table :data="tableData" row-key="id" style="width: 100%" max-height="650" ref="tableRef"
      @selection-change="handleSelectionChange" :header-cell-style="{ background: '#eef1f6', color: '#2c2c3b' }"
      @filter-change="handleFilterChange">
      <el-table-column type="selection" min-width="55"></el-table-column>
      <el-table-column fixed label="序号" min-width="60" align="center"> <!-- 固定表头 -->
        <template #default="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column fixed prop="studentId" label="学号" min-width="180" v-if="selectedColumns.includes('studentId')" />
      <!-- 固定表头 -->
      <el-table-column prop="name" label="姓名" min-width="100" v-if="selectedColumns.includes('name')" />
      <el-table-column label="性别" width="80" prop="gender" column-key="gender" v-if="selectedColumns.includes('gender')"
        :filters="[
          { text: '男', value: '男' },
          { text: '女', value: '女' }
        ]" :filter-method="filterHandler" :formatter="formatGender" />
      <el-table-column prop="birthDate" label="出生日期" sortable min-width="140"
        v-if="selectedColumns.includes('birthDate')" />
      <el-table-column prop="college" label="学院" min-width="140" v-if="selectedColumns.includes('college')" />
      <el-table-column prop="className" label="班级" min-width="160" v-if="selectedColumns.includes('className')" />
      <el-table-column prop="politicalAffiliation" label="政治面貌" min-width="100"
        v-if="selectedColumns.includes('politicalAffiliation')" />
      <el-table-column prop="nationality" label="民族" min-width="100" v-if="selectedColumns.includes('nationality')" />
      <el-table-column prop="contactNumber" label="电话" min-width="140"
        v-if="selectedColumns.includes('contactNumber')" />
      <el-table-column prop="idCard" label="身份证号码" min-width="220" v-if="selectedColumns.includes('idCard')" />
      <el-table-column prop="homeAddress" label="家庭住址" min-width="300" v-if="selectedColumns.includes('homeAddress')" />
      <el-table-column label="操作" align="center" fixed="right" min-width="130">
        <template #default="scope">
          <router-link :to="{ path: '/admin/club/clubPersonInfo', query: { id: scope.row.id } }"
            class="detail-btn">查看详细信息</router-link>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 底部分页导航栏 -->
  <div class="pageNav">
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :hide-on-single-page="true"
      layout="total,prev, pager, next,sizes" background :page-sizes="[5, 10, 20, 50]" :size="size" :total="total"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>

</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import type { ComponentSize } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { TableInstance } from 'element-plus';
import * as echarts from 'echarts';
import { exportExcel, exportPDF, queryInfo, agreeApply as apiAgreeApply, collegeCount } from '@/api/club/apply-info';


// 表格展示数据
let tableData = ref([])
// 获取表格实例
const tableRef = ref<TableInstance>();

// 查询参数定义
let qCollege = ref("") // 学院查询参数
let qGender = ref("")  // 性别查询参数
let qMajor = ref("")  // 性别查询参数


// 选中的成员信息
const selectedMembers = ref([])

//图表展示
const advanceCharts = ref(true);

//切换图表显示
function toggleAdvancedCharts() {
  advanceCharts.value = !advanceCharts.value;
}

// 分页相关数据
const size = ref<ComponentSize>('default')
const currentPage = ref(1)
const pageSize = ref(5)
let total = ref(0)

const selectedColumns = ref(['studentId', 'name', 'gender', 'birthDate', 'college', 'className', 'contactNumber']);

// 表格列选择相关
const columnOptions = ref([
  { label: '学号', value: 'studentId', disabled: true },
  { label: '姓名', value: 'name', disabled: true },
  { label: '性别', value: 'gender' },
  { label: '出生日期', value: 'birthDate' },
  { label: '学院', value: 'college' },
  { label: '班级', value: 'className' },
  { label: '政治面貌', value: 'politicalAffiliation' },
  { label: '民族', value: 'nationality' },
  { label: '电话', value: 'contactNumber' },
  { label: '身份证号码', value: 'idCard' },
  { label: '家庭住址', value: 'homeAddress' },
]);

// 格式化性别
function formatGender(row, column, cellValue) {
  const statusMap = {
    0: '女',
    1: '男',
  };
  return statusMap[cellValue] || '未知';
}
// 筛选男女性别
function filterHandler(value, row, column) {
  const property = column.property; // 当前列的属性名
  if (property === 'gender') {
    // 将 gender 的值转换为 '男' 或 '女'
    const genderText = row.gender === "1" ? '男' : row.gender === "0" ? '女' : '未知';
    return genderText === value; // 返回是否匹配筛选条件
  }

  return true; // 默认返回 true，表示不过滤
}
// 处理性别筛选
const handleFilterChange = (filters) => {
  // 获取筛选条件
  const genderFilter = filters.gender;
  if (genderFilter && genderFilter.length == 1) {
    // 将筛选条件存储到 qGender
    qGender.value = genderFilter[0] === '男' ? '1' : '0';
  } else {
    qGender.value = ''; // 清空筛选条件
  }
  // 发起请求
  conditionPageQuery(currentPage.value, pageSize.value);
};

// 导出相应的Excel
function downloadExcel(id, name) {
  exportExcel(id).then(response => {
    // console.log(result)
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `${name}.xlsx`); // 设置下载文件名
    document.body.appendChild(link);
    link.click();
    link.remove(); // 下载完成后移除元素
    setTimeout(() => {
      window.URL.revokeObjectURL(url);
    }, 1000); // 1 秒后释放，确保下载已经开始
  }).catch(error => {
    console.error("导出失败", error);
  })
}

// 导出信息为Excel
async function exportInfoToExcel() {
  if (selectedMembers.value.length === 0) {
    return ElMessage.warning('请先选择要导出的成员');
  }
  try {
    const downloadTasks = selectedMembers.value.map(member =>
      downloadExcel(member.id, member.name)
    );
    await Promise.all(downloadTasks);
    ElMessage.success('导出成功');
  } catch (error) {
    ElMessage.error('导出过程中发生错误');
  } finally {
    tableRef.value.clearSelection()
    selectedMembers.value = [];
  }
}


// 导出信息为PDF
async function exportInfoToPDF() {
  if (selectedMembers.value.length === 0) {
    return ElMessage.warning('请先选择要导出的成员');
  }
  try {
    const downloadTasks = selectedMembers.value.map(member => downloadPDF(member.id));
    await Promise.all(downloadTasks);
    ElMessage.success('导出成功');
  } catch (error) {
    ElMessage.error('导出过程中发生错误');
  } finally {
    tableRef.value.clearSelection()
    selectedMembers.value = [];
  }
}

// 导出信息为PDF
function downloadPDF(id) {
  exportPDF(id).then(response => {
    const blob = new Blob([response.data], { type: 'application/pdf' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;

    // 安全解析文件名
    const contentDisposition = response.headers['content-disposition'];
    let fileName = 'default.pdf';

    if (contentDisposition) {
      const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
      const matches = filenameRegex.exec(contentDisposition);

      if (matches?.[1]) {
        fileName = matches[1]
          .replace(/['"]/g, '')
          .replace(/^UTF-8''/i, '')
          .replace(/%20/g, ' ');
      }
    }
    link.setAttribute('download', decodeURIComponent(fileName));
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  }).catch(error => {
    console.error('下载失败:', error);
  });
}


// 组件实例挂载完成之后 调用函数获取相关数据
onMounted(() => {
  conditionPageQuery(currentPage.value, pageSize.value)
  getCollegeCount()
})

// 每页显示条目个数变化
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  conditionPageQuery(currentPage.value, val)
}

// 当前页码变化
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  conditionPageQuery(val, pageSize.value)
}






// 多选框 选择项发生变化时触发
function handleSelectionChange(selection) {
  // 提取所有选中行的 studentId
  selectedMembers.value = selection.map(item => ({
    id: item.id,
    name: item.name
  }))
}

// 条件查询获取预征班现役成员
function conditionPageQuery(page, pageSize) {
  const queryParams = {
    page,
    pageSize,
    gender: qGender.value,
    college: qCollege.value,
    className: qMajor.value
  }
  queryInfo(queryParams).then(result => {
    tableData.value = result.data.records
    total.value = result.data.total
  })
}

// 批量同意申请
function agreeApply() {
  // 将数组转换成以逗号分隔的字符串
  if (selectedMembers.value.length === 0) {
    ElMessage({
      message: '请先勾选对应的学生！',
      type: 'warning',
    })
    return;
  }
  const idsArray = selectedMembers.value.map(item => item.id);
  console.log(idsArray)
  apiAgreeApply(idsArray).then(result => {
    console.log(result)
    ElMessage({
      message: '操作成功',
      type: 'success',
    })
    conditionPageQuery(currentPage.value, pageSize.value)
  }).catch(error => {
    console.error("批量同意失败", error);
  });
}

let collegeData = ref([])

// 获取各个学院的总人数信息
function getCollegeCount() {
  collegeCount().then(result => {
    collegeData.value = result.data
    renderPieChart()
  })
}

const pieChart = ref(null);
// 渲染饼图
function renderPieChart() {
  if (!pieChart.value || collegeData.value.length === 0) return;
  const myChart = echarts.init(pieChart.value);

  // 格式化数据
  const chartData = collegeData.value.map(item => ({
    name: item.college,
    value: item.memberCount
  }));


  myChart.setOption({
    title: {
      text: '各学院人数比例',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)'
    },

    series: [
      {
        name: '学院人数',
        type: 'pie',
        center: ["50%", "50%"],
        radius: ["0%", "72%"],
        data: chartData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
      }

    ]
  });
};


</script>

<style scoped>
/* 操作按钮 */
.detail-btn {
  text-decoration: none;
  color: inherit;
  border: none;
  background: none;
  padding: 0;
  font: inherit;
  cursor: pointer;
  outline: none;
  background-color: #409eff;
  color: white;
  padding: 6px 16px;
  text-align: center;
  display: inline-block;
  font-size: 12px;
  border-radius: 5px;
}

.tableShow {
  width: 100%;
  flex-grow: 1;
  margin-top: 10px;
  font-size: 20px;
}


button {
  margin-left: 30px;
}

#top {
  margin-top: 10px;
  text-align: center;
}

/* 容器布局 */
.charts-container {
  display: flex;
  align-items: center;
  gap: 30px;
  background: #f8f9fa;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.advanced-btn-container {
  display: flex;
  justify-content: center;
  margin-bottom: 10px;
}

.secondary-btn {
  margin-right: 10px;
  padding: 8px 16px;
  font-size: 14px;
  background-color: #e4e7ed;
  color: #333;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

/* 数据卡片样式 */
.audit-count-card {
  min-width: 240px;
  padding: 25px;
  background: linear-gradient(135deg, #ffffff 0%, #f1f3f5 100%);
  border-radius: 12px;
  border: 1px solid #e9ecef;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: transform 0.2s;
}

.audit-count-card:hover {
  transform: translateY(-2px);
}

/* 头部样式 */
.count-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 15px;
  padding-bottom: 12px;
  border-bottom: 1px solid #dee2e6;
}

.notification-icon {
  font-size: 1.4em;
  color: #ff6b6b;
}

.count-title {
  font-size: 1.1em;
  color: #495057;
  font-weight: 500;
  letter-spacing: 0.5px;
}

/* 数字展示 */
.count-content {
  text-align: center;
  margin: 20px 0;
}

.highlight-number {
  font-size: 2.8em;
  font-weight: 700;
  color: #f03e3e;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
  margin-right: 5px;
}

.unit {
  font-size: 1.2em;
  color: #868e96;
  vertical-align: super;
}

/* 底部文字 */
.count-footer {
  text-align: center;
  color: #adb5bd;
  font-size: 0.9em;
  letter-spacing: 0.5px;
}



/* 设置父容器为flex布局 */
.charts-container {
  display: flex;
  justify-content: space-around;
  /* 子元素之间留有空间 */
  align-items: flex-start;
  /* 对齐方式为顶部对齐 */
}


/* 底部分页栏样式 */
.pageNav {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;
}

/* 列选择器 */
.columnSelector {
  display: flex;
  width: 1000px;
  align-items: center;
  margin: 10px auto;
}

/* 选择器标题 */
.selectorTitle {
  width: 130px;
}

input {
  border-radius: 8px;
}
</style>